package com.dvt.faceScan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.dvt.faceScan.httpUntil.XmlRpcUtils;
import com.dvt.faceScan.widget.Config;
import com.dvt.faceScan.widget.CustomDatePicker;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class employeeDetailActivity extends Activity implements View.OnClickListener {
    private EditText nameView;
    private EditText telView;
    private Button btnBirthday;
    private EditText salaryView;
    private EditText idcardView;
    private Button companyView;
    private String flag = "";
    private String create_result = "";
    private String update_result = "";
    private Button btn_save;
    private String name, sex, tel, project, company;
    private String ID;
    private String now_date;
    private boolean update_flag = false;
    public RadioGroup mRadioGroup1, mRadioGroup2;
    public RadioButton mRadio1, mRadio2, mRadio3, mRadio4;
    private employeeModel employee = new employeeModel();
    private CustomDatePicker customDatePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_employee_detail);

        Intent in = getIntent();
        flag = in.getStringExtra("flag");
        ID = in.getStringExtra("id");
        Log.d("wumh_debug", "------id=" + ID);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        now_date = df.format(new Date()).toString();// new Date()为获取当前系统时间
        initView();
        show();
        addListener();
        initDatePicker();
        if("2".equals(flag)){
            btnBirthday.setText("");
        }
    }

    private void initView() {
        nameView = (EditText) findViewById(R.id.grzl_name);
        telView = (EditText) findViewById(R.id.grzl_tel);
        companyView = (Button) findViewById(R.id.btn_company);
        btnBirthday = (Button) findViewById(R.id.btn_birthday);
        salaryView = (EditText) findViewById(R.id.grzl_salary);
        idcardView = (EditText) findViewById(R.id.grzl_idcard);
        btn_save = (Button) findViewById(R.id.Btn_save);
        if ("1".equals(flag)) {
            //btn_save.setVisibility(View.GONE);
            btn_save.setText("保存");
            update_flag = true;
        }

        mRadioGroup1 = (RadioGroup) findViewById(R.id.term_group);
        mRadio1 = (RadioButton) findViewById(R.id.long_term);
        mRadio2 = (RadioButton) findViewById(R.id.short_term);
        mRadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                String term = "";
                if (checkedId == mRadio1.getId()) {
                    term = "long";
                } else if (checkedId == mRadio2.getId()) {
                    term = "short";
                }
                employee.setTerm(term);
            }
        });

        mRadioGroup2 = (RadioGroup) findViewById(R.id.sex_group);
        mRadio3 = (RadioButton) findViewById(R.id.boy);
        mRadio4 = (RadioButton) findViewById(R.id.girl);
        mRadioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                String sex = "";
                if (checkedId == mRadio3.getId()) {
                    sex = "male";
                } else if (checkedId == mRadio4.getId()) {
                    sex = "female";
                }
                employee.setSex(sex);
            }
        });

        requestEmployeeDetail();
    }

    private void show() {
        nameView.setText(employee.getName());
        btnBirthday.setText(employee.getBirthday());
        telView.setText(employee.getIphone());
        salaryView.setText(employee.getSalary());
        idcardView.setText(employee.getIdcard());
        companyView.setText(employee.getCompany());
        if ("male".equals(employee.getSex())) {
            mRadio3.setChecked(true);
        } else if ("female".equals(employee.getSex())) {
            mRadio4.setChecked(true);
        }
        if ("long".equals(employee.getTerm())) {
            mRadio1.setChecked(true);
        } else if ("short".equals(employee.getTerm())) {
            mRadio2.setChecked(true);
        }
        nameView.requestFocus();
        nameView.setSelection(nameView.getText().length());
    }

    private void addListener() {
        btn_save.setOnClickListener(this);
        companyView.setOnClickListener(this);
        btnBirthday.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (btn_save == v) {
            if (update_flag) {
                update();
            } else {
                save();
            }
        } else if (companyView == v) {
            Intent intent = new Intent(employeeDetailActivity.this, ChoiseCompany.class);
            startActivityForResult(intent, 101);
        } else if (btnBirthday == v) {
            customDatePicker.show(now_date);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            companyView.setText(data.getStringExtra("gs"));
            employee.setCompanyId(data.getStringExtra("gsid"));
        }
    }


    private void save() {
        employee.setName(nameView.getText().toString());
        employee.setCompany(companyView.getText().toString());
        employee.setBirthday(btnBirthday.getText().toString());
        employee.setIphone(telView.getText().toString());
        employee.setIdcard(idcardView.getText().toString());
        employee.setSalary(salaryView.getText().toString());

        if (employee.getName().length() == 0) {
            Toast.makeText(this, getString(R.string.nameText),
                    Toast.LENGTH_SHORT).show();
            nameView.requestFocus();
            return;
        }
        if (employee.getSex().length() == 0) {
            Toast.makeText(this, getString(R.string.sexText),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (employee.getCompany().length() == 0) {
            Toast.makeText(this, getString(R.string.companyText),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (employee.getBirthday().length() == 0) {
            Toast.makeText(this, getString(R.string.ageText),
                    Toast.LENGTH_SHORT).show();
            btnBirthday.requestFocus();
            return;
        }
        if (employee.getIdcard().length() == 0) {
            Toast.makeText(this, getString(R.string.idcardText),
                    Toast.LENGTH_SHORT).show();
            idcardView.requestFocus();
            return;
        }

        saveEmployeeDetail();
        if (isNumeric(create_result)) {

            Toast.makeText(this, getString(R.string.savesuccessText),
                    Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(employeeDetailActivity.this, FaceActivity.class);
            intent.putExtra("id", "1");
            intent.putExtra("empID", create_result);
            startActivity(intent);
            finish();
        }
    }

    private void update() {
        employee.setName(nameView.getText().toString());
        employee.setCompany(companyView.getText().toString());
        employee.setBirthday(btnBirthday.getText().toString());
        employee.setIphone(telView.getText().toString());
        employee.setIdcard(idcardView.getText().toString());
        employee.setSalary(salaryView.getText().toString());

        if (employee.getName().length() == 0) {
            Toast.makeText(this, getString(R.string.nameText),
                    Toast.LENGTH_SHORT).show();
            nameView.requestFocus();
            return;
        }
        if (employee.getSex().length() == 0) {
            Toast.makeText(this, getString(R.string.sexText),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (employee.getCompany().length() == 0) {
            Toast.makeText(this, getString(R.string.companyText),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (employee.getBirthday().length() == 0) {
            Toast.makeText(this, getString(R.string.ageText),
                    Toast.LENGTH_SHORT).show();
            btnBirthday.requestFocus();
            return;
        }
        if (employee.getIdcard().length() == 0) {
            Toast.makeText(this, getString(R.string.idcardText),
                    Toast.LENGTH_SHORT).show();
            idcardView.requestFocus();
            return;
        }

        updateEmployeeDetail();

        if ("true".equals(update_result)) {
            Toast.makeText(this, getString(R.string.savesuccessText),
                    Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    public boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    //添加员工资料
    private void saveEmployeeDetail() {

        Callable<String> c = new Callable<String>() {
            @Override
            public String call() {
                int uid = 1;
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.hr_employee;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 121;

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("action", action_id);
                Map<String, Object> context = new HashMap<String, Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                Map<String, Object> kwargs = new HashMap<String, Object>();
                context.put("context", context);

                Map<String, Object> empObj = new HashMap<String, Object>();
                empObj.put("name", employee.getName());
                empObj.put("mobile_phone", employee.getIphone());
                empObj.put("gender", employee.getSex());
                empObj.put("birthday", employee.getBirthday());
                empObj.put("identification_id", employee.getIdcard());
                empObj.put("short_or_long", employee.getTerm());
                empObj.put("hired_company_id", employee.getCompanyId());
                empObj.put("salary", employee.getSalary());

                List args = asList(empObj);

                Map<String, Object> options = new HashMap<String, Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);

                Object o = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model, "create", args,
                        kwargs
                ));
                create_result = null;
                if (o != null) {
                    Log.d("wumh_debug", "" + o.toString());
                    create_result = o.toString();
                }
                return "";
            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try {
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("vvvvvv", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //查看员工资料
    public void requestEmployeeDetail() {
        Callable<String> c = new Callable<String>() {
            @Override
            public String call() {
                int empID = Integer.parseInt(ID);
                int uid = 1;
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.hr_employee;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 121;

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("action", action_id);
                Map<String, Object> context = new HashMap<String, Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);
                Map<String, Object> kwargs = new HashMap<String, Object>();
                kwargs.put("context", context);

                List args = asList(asList(empID), asList("name", "hired_company_id", "short_or_long", "mobile_phone", "gender", "birthday", "identification_id", "salary"));
                Map<String, Object> options = new HashMap<String, Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);
                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model, "read", args, kwargs));
                List r = asList((Object[]) requestObj);
                for (Object object : r) {
                    Map<String, Object> a = (HashMap) object;
                    String astr = String.valueOf(a.get("name"));
                    if (!"false".equals(String.valueOf(a.get("hired_company_id")))) {
                        Object[] o = (Object[]) a.get("hired_company_id");
                        List<Object> ol = asList(o);
                        employee.setCompanyId(ol.get(0).toString());
                        employee.setCompany(ol.get(1).toString());
                    }
                    String iphone = String.valueOf(a.get("mobile_phone"));
                    String id = String.valueOf(a.get("id"));
                    if (astr.equals("false")) {
                        astr = "";
                    } else {
                        employee.setName(astr);
                    }

                    if (iphone.equals("false")) {
                        iphone = "";
                    } else {
                        employee.setIphone(iphone);
                    }

                    if (id.equals("false")) {
                        id = "";
                    } else {
                        employee.setInfo(id);
                    }

                    if (String.valueOf(a.get("gender")).equals("false")) {
                    } else {
                        employee.setSex(String.valueOf(a.get("gender")));
                    }

                    if (String.valueOf(a.get("salary")).equals("false")) {
                    } else {
                        employee.setSalary(String.valueOf(a.get("salary")));
                    }

                    if (String.valueOf(a.get("birthday")).equals("false")) {
                    } else {
                        employee.setBirthday(String.valueOf(a.get("birthday")));
                    }

                    if (String.valueOf(a.get("birthday")).equals("false")) {
                    } else {
                        employee.setBirthday(String.valueOf(a.get("birthday")));
                    }

                    if (String.valueOf(a.get("short_or_long")).equals("false")) {
                    } else {
                        employee.setTerm(String.valueOf(a.get("short_or_long")));
                    }

                    if (String.valueOf(a.get("identification_id")).equals("false")) {
                    } else {
                        employee.setIdcard(String.valueOf(a.get("identification_id")));
                    }

                    Set<String> akeySet = a.keySet();
                    for (String key : akeySet) {
                        Log.d("mmmmmmmm", key + "-->" + a.get(key));
                    }
                }
                return "";

            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try {
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //更新员工资料
    public void updateEmployeeDetail() {
        Callable<String> c = new Callable<String>() {
            @Override
            public String call() {
                int empID = Integer.parseInt(ID);
                int uid = 1;
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.hr_employee;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 121;

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("action", action_id);
                Map<String, Object> context = new HashMap<String, Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);
                Map<String, Object> kwargs = new HashMap<String, Object>();
                kwargs.put("context", context);

                Map<String, Object> empObj = new HashMap<String, Object>();
                empObj.put("name", employee.getName());
                empObj.put("mobile_phone", employee.getIphone());
                empObj.put("gender", employee.getSex());
                empObj.put("birthday", employee.getBirthday());
                empObj.put("identification_id", employee.getIdcard());
                empObj.put("short_or_long", employee.getTerm());
                empObj.put("hired_company_id", employee.getCompanyId());
                empObj.put("salary", employee.getSalary());

                List args = asList(asList(empID), empObj);
                Map<String, Object> options = new HashMap<String, Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);
                Object result = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model, "write", args, kwargs));
                if (result != null) {
                    Log.d("wumh_debug", "" + result.toString());
                    update_result = result.toString();
                }
                return "";

            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try {
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //初始化日期控件
    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        btnBirthday.setText(now.split(" ")[0]);
        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                btnBirthday.setText(time.split(" ")[0]);
                telView.requestFocus();
                telView.setSelection(telView.getText().length());
            }
        }, "1970-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(false); // 不允许循环滚动
    }

    private List asList(Object... a) {
        return Arrays.asList(a);
    }

}
